package com.kk.base.controller.admin;

import com.kk.base.bean.CodeMsg;
import com.kk.base.bean.PageBean;
import com.kk.base.bean.Result;
import com.kk.base.entity.admin.Role;
import com.kk.base.entity.admin.User;
import com.kk.base.entity.admin.UserRoleTypeEnum;
import com.kk.base.entity.home.BranchApplyFor;
import com.kk.base.entity.home.BranchApplyForStatusEnum;
import com.kk.base.entity.home.BranchTypeEnum;
import com.kk.base.entity.home.HomeUser;
import com.kk.base.service.admin.OperaterLogService;
import com.kk.base.service.admin.RoleService;
import com.kk.base.service.admin.UserService;
import com.kk.base.service.home.BranchApplyForService;
import com.kk.base.util.SessionUtil;
import com.kk.base.util.ValidateEntityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 网点管理控制层
 */
@Slf4j
@RequestMapping("/admin/branches")
@Controller
public class BranchesController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OperaterLogService operaterLogService;

    @Autowired
    private BranchApplyForService branchApplyForService;

    /**
     * 网点列表页面
     *
     * @param model
     * @param user
     * @param pageBean
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Model model, User user, PageBean<User> pageBean) {
        model.addAttribute("title", "网点列表");
        model.addAttribute("username", user.getUsername());
        model.addAttribute("pageBean", userService.findList(pageBean, user.getUsername(), UserRoleTypeEnum.BRANCHES));
        return "admin/branches/list";
    }


    /**
     * 网点编辑页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, @RequestParam(name = "id") Long id) {
        model.addAttribute("roles", roleService.findAllByRoleType(UserRoleTypeEnum.BRANCHES));
        model.addAttribute("user", userService.find(id));
        return "admin/branches/edit";
    }

    /**
     * 编辑网点信息表单提交处理
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> edit(User user) {
        //用统一验证实体方法验证是否合法
        CodeMsg validate = ValidateEntityUtil.validate(user);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }
        if (user.getRole() == null || user.getRole().getId() == null) {
            return Result.error(CodeMsg.BRANCHES_USER_ROLE_EMPTY);
        }
        if (user.getId() == null || user.getId().longValue() <= 0) {
            return Result.error(CodeMsg.BRANCHES_USE_NO_EXIST);
        }
        if (userService.isExistUsername(user.getUsername(), user.getId())) {
            return Result.error(CodeMsg.ADMIN_USERNAME_EXIST);
        }
        //到这说明一切符合条件，进行数据库保存
        User findById = userService.find(user.getId());
        //讲提交的网点信息指定字段复制到已存在的user对象中,该方法会覆盖新字段内容
        BeanUtils.copyProperties(user, findById, "id", "createTime", "updateTime", "userType");
        if (userService.save(findById) == null) {
            return Result.error(CodeMsg.BRANCHES_USE_EDIT_ERROR);
        }
        operaterLogService.add("编辑网点，网点名：" + user.getUsername());
        return Result.success(true);
    }

    /**
     * 删除网点
     */
    @RequestMapping("/delete")
    public String delete(@RequestParam(name = "id") Long id) {
        log.info("网点ID={}", id);
        try {
            User user = userService.find(id);
            log.info("网点信息={}", user);
            if (user != null) {
                user.setStatus(0);
                userService.save(user);
                Long branchId = user.getBranchId();
                branchApplyForService.delete(branchId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/admin/branches/list";
    }


    @RequestMapping("/add")
    public String add(Model model, @RequestParam(name = "id") Long id) {
        log.info("添加网点");
        PageBean<BranchApplyFor> pageBean = new PageBean<>();
        User user = userService.find(id);
        model.addAttribute("pageBean", branchApplyForService.findList(pageBean, null, user.getId()));
        model.addAttribute("index", 6);
        model.addAttribute("branchTypes", BranchTypeEnum.values());
        return "home/branch/index";
    }

    /**
     * 网点申请保存
     *
     * @param branchApplyFor
     * @return
     */
    @RequestMapping(value = "/applyFor", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> applyFor(BranchApplyFor branchApplyFor) {
        branchApplyFor.setBranchApplyForStatus(BranchApplyForStatusEnum.VERIFYTHE);
        BranchApplyFor save = branchApplyForService.save(branchApplyFor);
        Long id = save.getId();
        System.out.println("网点ID" + id);
        log.info("执行成功===");
        Role role = roleService.findTop1ByRoleType(UserRoleTypeEnum.BRANCHES);
        if (role == null) {
            return Result.error(CodeMsg.BRANCHAPPLYFOR_ROLE_NO_EXIST);
        }
        Integer integer = branchApplyForService.agreeBranchApplyFor(id, role);
        if (1 == integer) {
            return Result.error(CodeMsg.BRANCHAPPLYFOR_THROUGH_ERROR);
        }
        return Result.success(true);
    }
}
